package fcrypt

import "fmt"

//曲路密码，先把数据存放到指定行列的矩阵中，在通过特定的顺序重排
func CurveEnc(plain string, col int) string {
	plainByte := []byte(plain)
	var row int
	plainLen := len(plainByte)
	if plainLen%col == 0 {
		row = plainLen / col
	} else {
		row = plainLen/col + 1
	}

	var matrics [][]byte
	for i := 0; i < row; i++ {
		a := make([]byte, col, col)
		matrics = append(matrics, a)
	}
	for i := 0; i < row*col; i++ {
		if i < plainLen {
			matrics[i/col][i%col] = plainByte[i]
		} else {
			matrics[i/col][i%col] = 0x30
		}
	}
	fmt.Println(matrics)

	cipherByte := make([]byte, row*col, row*col)
	group := 0
	for k := 0; k < row*col; k++ {
		i := 0
		if group%2 == 0 {
			i = row - k%row - 1
		} else {
			i = k % row
		}
		j := col - k/row - 1
		cipherByte[k] = matrics[i][j]
		group++
	}
	cipherStr := string(cipherByte)
	fmt.Println(cipherStr)
	return cipherStr
}

func CurveDec(cipher string, col int) string {
	cipherByte := []byte(cipher)
	cipherLen := len(cipherByte)
	if cipherLen%col != 0 {
		fmt.Printf("曲路解密错误 col = %d\n", col)
		return ""
	}

	row := cipherLen / col
	var matrics [][]byte
	for i := 0; i < row; i++ {
		a := make([]byte, col, col)
		matrics = append(matrics, a)
	}

	group := 0
	for k := 0; k < row*col; k++ {
		i := 0
		if group%2 == 0 {
			i = row - k%row - 1
		} else {
			i = k % row
		}
		j := col - k/row - 1
		matrics[i][j] = cipherByte[k]
		group++
	}
	fmt.Println(matrics)

	plainByte := make([]byte, row*col, row*col)
	for i := 0; i < row*col; i++ {
		plainByte[i] = matrics[i/col][i%col]
	}
	plainStr := string(plainByte)
	return plainStr
}
